const pool = require('./db');

async function createLog(req, { message, tp = null, obj_json = null, location = null, user_id = null } = {}) {
  try {
    const uid = user_id || (req && req.user && req.user.id) || 0;
    const ip = req && (req.headers && (req.headers['x-forwarded-for'] || req.headers['X-Forwarded-For'])) || (req && (req.ip || (req.connection && req.connection.remoteAddress))) || null;

    // produce a MySQL DATETIME string for Beijing time (UTC+8) regardless of server timezone
    const beijingDatetime = (() => {
      // add 8 hours to UTC timestamp so that using UTC getters yields Beijing time
      const beijingMs = Date.now() + 8 * 60 * 60 * 1000;
      const d = new Date(beijingMs);
      const YYYY = d.getUTCFullYear();
      const MM = String(d.getUTCMonth() + 1).padStart(2, '0');
      const DD = String(d.getUTCDate()).padStart(2, '0');
      const hh = String(d.getUTCHours()).padStart(2, '0');
      const mm = String(d.getUTCMinutes()).padStart(2, '0');
      const ss = String(d.getUTCSeconds()).padStart(2, '0');
      return `${YYYY}-${MM}-${DD} ${hh}:${mm}:${ss}`;
    })();

    await pool.query(
      'INSERT INTO atb_log (time_stamp, message, user_id, ip, location, tp, obj_json) VALUES (?, ?, ?, ?, ?, ?, ?)',
      [beijingDatetime, message || '', uid, ip, location || null, tp || null, obj_json || null]
    );
  } catch (err) {
    // Do not throw — logging failure should not break main flow
    console.error('Failed to write log:', err);
  }
}

module.exports = { createLog };